<!DOCTYPE html>
<html lang="en">

<head>   
    <meta charset="UTF-8">    <title>Echarts实现心电图效果</title>   
    <script src="https://cdn.bootcss.com/echarts/3.7.1/echarts.js"></script>
</head>

<body>
    <div id="totalFlowRate" style="height:300px;"></div>
</body>

</html>
<script type="text/javascript">
let ws = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        //【非必须】 在ws后面添加了些内容
        var str = 'abc';
        //【非必须】 Sec-WebSocket-Protocol的内容
        var protocol = ['Sec-WebSocket-Protocol的内容']
        ws = new WebSocket("ws://127.0.0.1/ws/123214" + str);
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
 
    //连接发生错误的回调方法
    ws.onerror = function () {
        setMessageInnerHTML("error");
    };
 
    //连接成功建立的回调方法
    ws.onopen = function(event) {
        setMessageInnerHTML("success");
    }
    //接收到消息的回调方法
    ws.onmessage = function(message) {
        if (typeof(message.data) == 'string') {
            setMessageInnerHTML(message.data);
        }
    }
    //ws连接断开的回调方法
    ws.onclose = function(e) {
        setMessageInnerHTML("close");
    }
 
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
	debugger;
		var a = Math.round(Math.random() * 1000);
		let arr = innerHTML.split(",");
		arr.forEach(function(item) {
			//sleep(50);
			greet(item);
		});
        
    }
 
    //关闭连接
    function closeWebSocket() {
        ws.close();
    }
	 function sleep(time) {
	  return new Promise((resolve) => setTimeout(resolve, time));
	}
 
    //发送消息
    function send(msg) {
        if(!msg){
            msg = document.getElementById('text').value;
            document.getElementById('message').innerHTML += "send:" + msg + '<br/>';
            ws.send(msg);
        }
    }
	
    var totalFlowRate = echarts.init(document.getElementById('totalFlowRate'));
var xAxisData = [];
var yAxisData = [];
for (var i = 5000; i > 0; i--) {
    xAxisData.push(i + "秒前");
}
for (i = 1; i < 5001; i++) {
    yAxisData.push(null);
}
var totalFlowRateOption = {
    animation: false,
    title: {
        text: '心率（kbps）'/*,      
        left:"110px"*/ },
    tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
    },
    grid: {
        left: 50/*"50px"*/,
        right: 15/*"15px"*/
    },
    legend: {
        data: ['心率']
    },
    xAxis: {
        boundaryGap: false,
        data: xAxisData
    },
    yAxis: { boundaryGap: false },
    series: {
        symbol: "none",/*去掉小圆点*/
        name: '心率',
        type: 'line',
        data: yAxisData/*,             smooth:true//显示为平滑的曲线*/
    }
};

totalFlowRate.setOption(totalFlowRateOption);
/*
setInterval(function () { 
    var a = Math.round(Math.random() * 1000);
	greet(1);
}, 100);
*/
function greet(value) {
     yAxisData.push(value); 
    if(yAxisData.length>5000) {
        yAxisData.shift(); 
    }
    totalFlowRate.setOption(totalFlowRateOption); 
}

</script>